/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.auth.shiro.filter.authc;

import java.awt.image.BufferedImage;
import java.util.Collection;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.zfes.snowy.auth.AuthConsts;
import org.zfes.snowy.core.util.ZWebUtil;

import com.google.code.kaptcha.Producer;

public class SnowyCapchaProducerFilter extends PathMatchingFilter {
	
	private String captchaImageUrl =  AuthConsts.CAPTCHA.DEFAULT_CAPTCHA_IMAGE_URL;
	
	private Producer captchaProducer;
	@Override
	protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)throws Exception {
		    HttpServletResponse httpResponse = ZWebUtil.toHttp(response);
	   		
	        httpResponse.setDateHeader("Expires", 0);  
	        httpResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
	        httpResponse.addHeader("Cache-Control", "post-check=0, pre-check=0");  
	        httpResponse.setHeader("Pragma", "no-cache");  
	        httpResponse.setContentType("image/jpeg"); 
	        
	        String capText = captchaProducer.createText();  
	        Session session=SecurityUtils.getSubject().getSession();
	        System.out.println("SnowyCapchaProducerFilter--Session----sessionid:---||"+session.getId());
	        session.setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);   // store the text in the session 
	        Collection<Object> sd= session.getAttributeKeys();
	        sd.forEach(val->{System.out.println("SnowyCapchaProducerFilter--Session----sessionid:---AttributeKeys||"+val);});
	        BufferedImage bi = captchaProducer.createImage(capText);  // create the image with the text  
	        ServletOutputStream out = response.getOutputStream();  
	        ImageIO.write(bi, "jpg", out);  
	        try {  
	            out.flush();  
	        } finally {  
	            out.close();  
	        }  
	        return false;
	}
	public String getCaptchaImageUrl() {
		return captchaImageUrl;
	}
	public void setCaptchaImageUrl(String captchaImageUrl) {
		this.captchaImageUrl = captchaImageUrl;
	}
	public Producer getCaptchaProducer() {
		return captchaProducer;
	}
	public void setCaptchaProducer(Producer captchaProducer) {
		this.captchaProducer = captchaProducer;
	}
	
	
}
